package cms_category

import (
	"fmt"
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/core"
	util2 "gitee.com/binny_w/go-util/v2"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

var MdlCmsCategory *partner.TableModel

func init() {
	core.WaitCore.Wait()
	alias := "category"
	MdlCmsCategory = partner.NewTableModel(core.CmsCategory, alias, nil)
	defer core.Engine.RouterWithModel(core.ApiGroup, MdlCmsCategory)

	// insert fixer
	MdlCmsCategory.InsertFixer = func(_ *gin.Context, row *util2.MysqlRow) error {
		if !row.Has("key") || row.ToStr("key") == "" {
			return fmt.Errorf("栏目标识不能为空")
		}
		if row.ToStr("label") == "" {
			row.Set("label", row.ToStr("key"))
		}
		row.Set("created_at", time.Now().Unix())
		return nil
	}

	// list as tree
	MdlCmsCategory.UnregisterGinHandler(http.MethodGet, "/"+alias)
	MdlCmsCategory.UnregisterGinHandler(http.MethodGet, "/"+alias+"/:id")
	_ = MdlCmsCategory.RegisterGinHandler(http.MethodGet, "/"+alias, func(c *gin.Context) {
		tree, err := Tree(c)
		if err != nil {
			partner.WriteJsonError(c, 600, err.Error())
			return
		}
		if c.Query("for_search") != "" {
			partner.WriteJsonSuccess(c, tree.ExportForSearch())
			return
		}
		partner.WriteJsonSuccess(c, tree.Export())
	})

	afterChange := func(c *gin.Context) {
		c.Next()
		core.Cache.Del("all-category-tree")
	}
	beforeDelete := func(c *gin.Context) {
		if id := c.Param("id"); id != "" {
			if row, err := core.CmsCategory.GetOne(c, id); err == nil {
				c.Set("category_to_delete", row.ToStr("key"))
			}
		}
		c.Next()
	}
	afterDelete := func(c *gin.Context) {
		c.Next()
		if key := c.GetString("category_to_delete"); key != "" {
			query := fmt.Sprintf(
				"UPDATE `%s` SET `category_key` = '' WHERE `category_key` = ?",
				core.CmsArticle.Name,
			)
			_, _ = core.CmsArticle.Update(c, query, key)
		}
	}
	_ = MdlCmsCategory.UseGinMiddlewares(http.MethodPost, "/"+alias, afterChange)
	_ = MdlCmsCategory.UseGinMiddlewares(http.MethodDelete, "/"+alias+"/:id", beforeDelete, afterChange, afterDelete)
	_ = MdlCmsCategory.UseGinMiddlewares(http.MethodPatch, "/"+alias+"/:id", afterChange)
}
